﻿using System;
using System.IO;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using ACM.cmsarea08.Administration.Core;
using ACM.cmsarea08;


namespace ACM.cmsarea08.Administration.Controls {
	
	
    [DefaultProperty("SelectedSection")]
    [ToolboxData("<{0}:DropDownSezioni runat=server></{0}:DropDownSezioni>")]
	public class DropDownSezioni : DropDownList {
		private string _lingua = null;
		private string _voceSel = "-1";
		private bool _managed = false;
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet dsMenu {
			get {
				if(ViewState["AC_Sezioni"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_Sezioni"];
			}
			set {
				ViewState["AC_Sezioni"] = value;
			}
		}

		
		public bool OnlyManaged {
			get { return _managed ; }
			set { _managed = value; }
		}
		//private string _SelectedSection; 
		public string SelectedSection
		{
		    get
		    {
//		    	return SelectedSection;
		        int selectedIndex = this.SelectedIndex;
		        if (selectedIndex >= 0)
		        {
		            return this.Items[selectedIndex].Value;
		        }
		        if(ViewState[this.ID + "selectedsec"]!=null)
		        	return ViewState[this.ID + "selectedsec"].ToString();
		        return string.Empty;
		    }
		    set
		    {
		    	
		    	bool found = false;
		    	if(this.Items.Count>0) {
		    		for(int i=0;i<this.Items.Count;i++){
		    			if(this.Items[i].Value == value) {
		    				found = true;break;			
		    			}
		    		}
		    	}
		    	if(found) {
			    	ViewState[this.ID + "selectedsec"] = value;
			        base.SelectedValue = value;
		    	} 	        
		    }
		}
		
		private void CaricaDati() {
			if(dsMenu==null) {
				if(ACM.cmsarea08.Users.CurrentUser.Autorizzato)
					dsMenu = dclass.getAdminContent(Users.CurrentUser.PrefLanguage,ContentManagerTypes.Sezioni,_managed);
				else
					dsMenu = dclass.getAdminContent(mainconfiguration.MainConf.LinguaPredefinita,ContentManagerTypes.Sezioni,_managed);
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
			this.Items.Add(new ListItem(" -- ","-1"));
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++)
				this.Items.Add(new ListItem(
					dsMenu.Tables[0].Rows[i]["titolo"].ToString(),
					dsMenu.Tables[0].Rows[i]["id"].ToString()));
			if(this.SelectedSection==string.Empty)
				this.Items[0].Selected=true;
			
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {
				
				/*
				if(this.SelectedSection!="-1" && this.Items.Count>0) {
					this.SelectedValue = this.SelectedSection.ToString();
				}
				*/
			}
			//varifica selezione:
		}
		/*
        protected override void Render(HtmlTextWriter output)
        {
			if (!Visible)
				return;
			StringWriter writer = new StringWriter();
			HtmlTextWriter buffer = new HtmlTextWriter(writer);
			base.Render(buffer);
			string testo = writer.ToString();
			string opzioni = "";
			//trova la prima occorrenza di <option
			int Spos = testo.IndexOf("<option");
			int Epos = testo.LastIndexOf("</select>") ;
			//trovata la posizione 
			opzioni = testo.Substring(Spos,Epos-Spos);
			testo = testo.Substring(0,Spos) + "{0}" + testo.Substring(Epos);
			//crea un regex per avere le opzioni come dico io.
			Regex r = new Regex("<option");  
			string[] opts = r.Split(opzioni);
			string nopzioni = "";
			const string valsearch = "value=\"";
			for(int i=0; i<opts.Length; i++) {
				//base 1 <option
				//la fine non è un problema.
				string temp = "";
				int sel =opts[i].IndexOf("selected");
				int val =opts[i].IndexOf(valsearch);
				if(val==-1) {
					continue;
				}
				//temp = opts[i].Substring(val+valsearch.Length);
				int valE=opts[i].IndexOf("\"",(val+valsearch.Length));
				if(sel!=-1 || val!=-1) {
					string valore = opts[i].Substring(val+valsearch.Length, valE-(val+valsearch.Length));
					if(valore!=this.SelectedSection && sel!=-1) {
						//elimina tag seledted
						opts[i] = opts[i].Replace("selected=\"selected\"","");
					} 
					if(valore ==this.SelectedSection) {
						if(sel==-1) {
							//aggiungi tag selected:
							opts[i] = "selected=\"selected\" " + opts[i];
						}
					}
					nopzioni +="<option "+opts[i] ;
				}
			}
			output.Write( "CIAO<br>" + this.SelectedSection + "<hr>"+(
				string.Format(testo,nopzioni)
			) );
//			output.Write( HttpUtility.HtmlEncode(
//				string.Format(testo,nopzioni)
//			) );			
			return;			
        }		
        */
	}
	
    [DefaultProperty("SelectedCategory")]
    [ToolboxData("<{0}:DropDownCategorie runat=server></{0}:DropDownCategorie>")]    
    public class DropDownCategorie : DropDownList {
		private string _lingua = null;
		private string _voceSel = "-1";
		private string _filter = "";
		private bool _managed = false;
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();

		public bool OnlyManaged {
			get { return _managed ; }
			set { _managed = value; }
		}
		
		private DataSet dsMenu {
			get {
				if(ViewState["AC_CAtegorieX"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_CAtegorieX"];
			}
			set {
				ViewState["AC_CAtegorieX"] = value;
			}
		}
		public string SectionFilter {
			get{
                return _filter;
			}
			set{

                if(string.IsNullOrEmpty(_filter))
                    dsMenu = null;
                else if (_filter != value)
                    dsMenu = null;

                _filter = value;
                if (dsMenu == null)
                {
                    CaricaDati();
                }
			}
		}
		public string SelectedCategory {
		    get
		    {
//		    	return SelectedSection;
		        int selectedIndex = this.SelectedIndex;
		        if (selectedIndex >= 0)
		        {
		            return this.Items[selectedIndex].Value;
		        }
		        if(ViewState[this.ID + "selectedcat"]!=null)
		        	return ViewState[this.ID + "selectedcat"].ToString();
		        return string.Empty;
		    }
		    set
		    {
		    	bool found = false;
		    	if(this.Items.Count>0) {
		    		for(int i=0;i<this.Items.Count;i++){
		    			if(this.Items[i].Value == value) {
		    				found = true;
		    				break;
		    			}
		    		}
		    	}
		    	if(found) {
			    	ViewState[this.ID + "selectedcat"] = value;
			        base.SelectedValue = value;
		    	} 
		    }
		}		
		private void CaricaDati() {
			if(dsMenu==null) {
				if(ACM.cmsarea08.Users.CurrentUser.Autorizzato)
                    dsMenu = dclass.getAdminContent(Users.CurrentUser.PrefLanguage, ContentManagerTypes.Categorie, SectionFilter,_managed);
				else
                    dsMenu = dclass.getAdminContent(mainconfiguration.MainConf.LinguaPredefinita, ContentManagerTypes.Categorie, SectionFilter,_managed);
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
            this.Items.Clear();
			this.Items.Add(new ListItem(" -- ","-1"));
            for (int i = 0; i < dsMenu.Tables[0].Rows.Count; i++)
            {
                ListItem itemo = new ListItem(
                    dsMenu.Tables[0].Rows[i]["titolo"].ToString(),
                    dsMenu.Tables[0].Rows[i]["id"].ToString());
                //HttpContext.Current.Response.Write("ITEM:  " + itemo.Value + " --:: " + SelectedCategory + "</br>");
                //if (itemo.Value == SelectedCategory)
                //    itemo.Selected = true;
                this.Items.Add(itemo);
            }
			if(this.SelectedCategory==string.Empty)
				this.Items[0].Selected=true;
		}

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
	
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {
				
				/*
				if(this.SelectedCategory!="-1" && this.Items.Count>0) {
					this.SelectedValue = this.SelectedCategory.ToString();
				}
				*/
			}
			//base.OnLoad(e);		
		}
	}
	
    [DefaultProperty("SelectedViewBlock")]
    [ToolboxData("<{0}:DropDownBVisivo runat=server></{0}:DropDownBVisivo>")]    
    public class DropDownBVisivo : DropDownList {
		private string _lingua = null;
		private string _voceSel = "-1";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet dsMenu {
			get {
				if(ViewState["AC_BlocchiVX"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_BlocchiVX"];
			}
			set {
				ViewState["AC_BlocchiVX"] = value;
			}
		}
		public string SelectedViewBlock {
		    get
		    {
//		    	return SelectedSection;
		        int selectedIndex = this.SelectedIndex;
		        if (selectedIndex >= 0)
		        {
		            return this.Items[selectedIndex].Value;
		        }
		        if(ViewState[this.ID + "selectedBV"]!=null)
		        	return ViewState[this.ID + "selectedBV"].ToString();
		        return string.Empty;
		    }
		    set
		    {
		    	bool found = false;
		    	if(this.Items.Count>0) {
		    		for(int i=0;i<this.Items.Count;i++){
		    			if(this.Items[i].Value == value) {
		    				found = true;break;			
		    			}
		    		}
		    	}
		    	if(found) {
			    	ViewState[this.ID + "selectedBV"] = value;
			        base.SelectedValue = value;
		    	} 	        
		    }
		}
		private void CaricaDati() {
			if(dsMenu==null) {
				dsMenu = dclass.GetDropAdminBlocchiVisivi();
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
			this.Items.Add(new ListItem(" -- ","-1"));
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++)
				this.Items.Add(new ListItem(
					dsMenu.Tables[0].Rows[i]["titolo"].ToString(),
					dsMenu.Tables[0].Rows[i]["id"].ToString()));
			if(this.SelectedViewBlock==string.Empty)
				this.Items[0].Selected=true;
		}

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
	
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {
				
				/*
				if(this.SelectedCategory!="-1" && this.Items.Count>0) {
					this.SelectedValue = this.SelectedCategory.ToString();
				}
				*/
			}
			//base.OnLoad(e);		
		}
	}

    [DefaultProperty("SelectedContent")]
    [ToolboxData("<{0}:DropDownChooseContent runat=server></{0}:DropDownChooseContent>")]        
    public class DropDownChooseContent : WebControl {
		
    	public DropDownChooseContent():base("div") {
    		
    	}
    	
		protected DropDownSezioni sezioni;
		protected HtmlSelect categorie;
//		protected HtmlInputText valore;
		protected HtmlInputHidden valore;
		private string _layout;
		private bool _bmanaged = false;

		public string Layout {
			get {
				return _layout;
			}
			set {
				_layout = value;
			}
		}
		public bool OnlyManaged {
			get {
				return _bmanaged;
			}
			set {
				_bmanaged = value;
			}
		}
		
		public string JavascriptHiddenValue {
			get {
				return this.valore.ClientID;
			}
		}
		public string SelectedContent {
			get {
				string alp = valore.Value.Replace("[","");
				alp = alp.Replace("\'","");
				alp = alp.Replace(",","~");
				alp = alp.Replace("]","");
				
				return alp;
			}
			set {
				if(value.IndexOf("~")!=-1) {
					string[] s = value.Split('~');
					sezioni.SelectedSection = s[0];
					valore.Value = "['" + s[0] + "','" + s[1] + "']";
				} else {
					if(value.Trim()!="") {
						sezioni.SelectedSection =value;
						valore.Value = "['" + value + "']";
					}
				}
			}
			
		}
		override protected void OnInit(EventArgs e)
		{
			sezioni = new DropDownSezioni();
			sezioni.OnlyManaged = OnlyManaged;
			sezioni.ID = this.ID + "sel_Sez";
			categorie = new HtmlSelect();
			categorie.ID = this.ID + "sel_cat";
			
			//categorie.InnerHtml= ("<option value=\"-1\">--</option>");
			//valore = new HtmlInputHidden();
			valore = new HtmlInputHidden();
			
			valore.ID = this.ID + "sel_hid";
			
			categorie.Style.Add("display","none");
			if(this.Layout!="table") {
				this.Controls.Add(sezioni);
				this.Controls.Add(categorie);
				this.Controls.Add(valore);
				this.Controls.Add(new LiteralControl(getJavaScript()));
			} else {
				this.Controls.Add(new LiteralControl("<table><tr><td>"));
				this.Controls.Add(sezioni);
				this.Controls.Add(new LiteralControl("</td><td>"));
				this.Controls.Add(categorie);
				this.Controls.Add(valore);
				this.Controls.Add(new LiteralControl("</td></tr></table>"));
				this.Controls.Add(new LiteralControl(getJavaScript()));
			}
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
	
		private void Page_Load(object o , EventArgs e) {		
			
			
			//base.OnLoad(e);		
		}
		
		private string getJavaScript() {
			string currentLang = "";
			if(ACM.cmsarea08.Users.CurrentUser.Autorizzato)
				currentLang = Users.CurrentUser.PrefLanguage;
			else
				currentLang = mainconfiguration.MainConf.LinguaPredefinita;
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			sb.Append("<script language=\"javascript\" type=\"text/javascript\">\n\r//<![CDATA[\n\r");
			sb.Append("var xml_" + this.ClientID + ";");
			sb.Append("function InitMe" + this.ID + "() {");
			sb.Append("var cont = document.getElementById('" +this.ClientID + "');");
			sb.Append("if(cont==null) return; ");
			sb.Append("var opsel = cont.getElementsByTagName('select');");
			sb.Append("var regSEZ = new RegExp(\"sel_Sez$\");");
			sb.Append("var regCAT = new RegExp(\"sel_cat$\");");
			sb.Append(" InitCategory" +this.ID+ "(); ");
			sb.Append("for(var i=0;i<opsel.length;i++) { ");
			sb.Append(" if(regSEZ.test(opsel[i].getAttribute('id') ) ) ");
			sb.Append("   opsel[i].onchange=SelectedSEZ" +this.ID+ ";");
			sb.Append(" if(regCAT.test(opsel[i].getAttribute('id') ) ) ");
			sb.Append("   opsel[i].onchange=SelectedCAT" +this.ID+ ";");
			sb.Append("}");
			sb.Append("} ");
			sb.Append("function SelectedSEZ" +this.ID+ "(e) { ");
			sb.Append("e = e || event; ");
			sb.Append("var obj = e.target || e.srcElement; ");
			sb.Append("var valCont = document.getElementById('" + valore.ClientID + "');");
			//cerca il controllo VALORE E INSERISCI LA SCELTA POI CHIAMA FUNZ CATEGO_INIT();
			sb.Append("if(valCont!=null)");
			sb.Append("valCont.value = '[\\'' + obj.value + '\\']';");
			sb.Append("InitCategory" + this.ID + "();");
			sb.Append("valCont=null;");
			sb.Append("}");
			sb.Append("function SelectedCAT" +this.ID+ "(e) { ");
			sb.Append("e = e || event; ");
			sb.Append("var obj = e.target || e.srcElement; ");
			//ottieni l'arrya e push il nuovo valore.
			sb.Append("var valVal = document.getElementById('" + valore.ClientID + "');");
			sb.Append("if (valVal==null) return;");
			sb.Append("var valori = eval(valVal.value);");
			sb.Append("if(valori.length>0) { " +
			          "valVal.value = '[\\'' + valori[0] + '\\''; }");
			sb.Append("if(obj.value!='-1') ");
			sb.Append(" valVal.value = valVal.value + ',\\'' + obj.value + '\\'';");
			
			sb.Append(" valVal.value = valVal.value +']';");
			sb.Append(" valVal = null; ");
			sb.Append("}");
			sb.Append("function InitCategory" +this.ID+ "() { ");
			sb.Append("var valVal = document.getElementById('" + valore.ClientID + "');");
			sb.Append("var valor;");
			sb.Append("if (valVal==null) return;");
			sb.Append(" if(valVal.value=='') return; ");
			sb.Append(" valor = eval(valVal.value);");
			sb.Append(" if(valor==null) return; ");
			sb.Append("if (valor.length>0) {");
			sb.Append(" ResetCateg" +this.ClientID+ "(); if(valor[0]=='-1') { ResetCateg" +this.ClientID+ "();return; }");
			//dentro l'if
			sb.Append(" else CaricaXML" + this.ID + "('/administration/Core/xml_server.asmx/getCategoriesbySec?lingua="+currentLang+"&sezione=' + valor[0]+'&managed="+this.OnlyManaged+"');");
			sb.Append("} valVal = null;");
			sb.Append("}");
			//funzione apri xml
			sb.Append("\nfunction CaricaXML" + this.ID + "(url) { \n");
			sb.Append(" xml_" + this.ClientID + "=null; \n");
			//sb.Append(" alert(url); ");
			sb.Append("if (window.XMLHttpRequest) xml_" + this.ClientID + "=new XMLHttpRequest(); \n");
			sb.Append("else if (window.ActiveXObject) xml_" + this.ClientID + "=new ActiveXObject(\"Microsoft.XMLHTTP\");\n");
			sb.Append("if (xml_" + this.ClientID + "!=null) { \n");
			sb.Append("	xml_" + this.ClientID + ".onreadystatechange=XmlReady"+this.ClientID+"; \n");
			sb.Append(" xml_" + this.ClientID + ".open(\"GET\",url,true); \n");
			sb.Append(" xml_" + this.ClientID + ".send(null); \n");
			sb.Append(" } else alert('No Xml support.'); \n");
			sb.Append("} \n");
			sb.Append("function XmlReady"+this.ClientID+"() { \n");
			sb.Append(" if (xml_" + this.ClientID + ".readyState==4) { \n");
			sb.Append(" if (xml_" + this.ClientID + ".status==200) { \n");
			sb.Append(" if( xml_" + this.ClientID + ".responseText == null) { ");
			sb.Append(" ResetCateg" +this.ClientID+ "(); alert('no dati'); return; }");
			
			sb.Append(" else { ");
			//carica valori nel controllo.
			sb.Append(" var dati = xml_" + this.ClientID + ".responseXML.getElementsByTagName(\"Table\");");
			sb.Append(" var valCat =document.getElementById('" + categorie.ClientID + "');");
			sb.Append(" var valVal =document.getElementById('" + valore.ClientID + "');");
			sb.Append(" var valorie;if(valVal!=null) valorie = eval(valVal.value);");
			sb.Append(" if( valCat==null) return; ");
			//sb.Append(" alert('sono qui:' + dati.length); ");
			sb.Append(" if(dati.length>0) { ");
			sb.Append(" valCat.style.display='block';");
			sb.Append(" valCat.options[valCat.options.length] =new Option('--','-1');");
			sb.Append(" } else ResetCateg" +this.ClientID+ "(); ");
			sb.Append(" for( var i=0; i<dati.length; i++ ) { \n");
			sb.Append(" valCat.options[valCat.options.length] =new Option( XMLItem" +this.ClientID+ "(dati[i],'titolo')," +
			          "XMLItem" +this.ClientID+ "(dati[i],'id'));");
			sb.Append("if(valorie!=null && valorie.length>1) {" +
			          "	if(valCat.options[valCat.options.length-1].value==valorie[1]) " +
			          "		valCat.options[valCat.options.length-1].selected=true;" +
			          "}");
			sb.Append(" \n} ");
			sb.Append(" } ");
			sb.Append(" } else { ResetCateg" +this.ClientID+ "();alert('Errore Reading XML');}  } \n");
			sb.Append("}\n");
			//leggi elemento xml 
			sb.Append(" function XMLItem" +this.ClientID+ "(itemxml,xmltag) { ");
			sb.Append(" var tmpElement = null; ");
			sb.Append(" tmpElement = itemxml.getElementsByTagName(xmltag)[0]; ");
			sb.Append(" if (tmpElement != null) {" +
			          " return unescape(tmpElement.childNodes[0].nodeValue); } ");
			sb.Append(" return 'vuoto'");
			sb.Append("}\n\r");
			//function resetta WAITING 
			sb.Append(" function ResetAll" +this.ClientID+ "() { ");

			sb.Append("}\n");
			//function resetta Categorie
			sb.Append(" function ResetCateg" +this.ClientID+ "() { ");
			sb.Append("var valCat = document.getElementById('" + categorie.ClientID + "');");
			sb.Append("if (valCat==null) return;");
			sb.Append("while(valCat.length>0) ");
			sb.Append("		valCat.remove(valCat.length-1);");
			sb.Append("valCat.style.display='none';");
			sb.Append("valCat=null;");
			sb.Append("}\n");
			
			sb.Append("InitMe" + this.ID + "();");
			sb.Append("\n\r//]]>\n\r</script>");
			return sb.ToString();
		}
		
	}
	
    [DefaultProperty("SelectedMenuItem")]
    [ToolboxData("<{0}:MenuTree runat=server Text=''></{0}:MenuTree>")]
	public class MenuTree : ListBox{
		
		private string _lingua = null;
		private string _MenuSel = "-1";
		private string _tipomodu = "";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet dsMenu {
			get {
				if(ViewState["AC_TreeMenuItem"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_TreeMenuItem"];
			}
			set {
				ViewState["AC_TreeMenuItem"] = value;
			}
		}
		public int maxsize {
			get {
				if(ViewState["AC_TreeMenuMaxsize"]==null)
					return 10;
				else
					return (int)ViewState["AC_TreeMenuMaxsize"];
			}
			set {
				ViewState["AC_TreeMenuMaxsize"] = value;
			}
		}
//		public bool Multiple {
//			get {
//				if(ViewState["AC_TreeMenuMultiple"]==null)
//					return 10;
//				else
//					return (int)ViewState["AC_TreeMenuMultiple"];
//			}
//			set {
//				ViewState["AC_TreeMenuMultiple"] = value;
//			}
//		}
		public bool MostraRoot {
			get {
				if(ViewState["AC_TreeMenuMostraRoot"]==null)
					return true;
				else
					return Convert.ToBoolean(ViewState["AC_TreeMenuMostraRoot"]);
			}
			set {
				ViewState["AC_TreeMenuMostraRoot"] = value;
			}
		}
		private DataSet dsMenuNames {
			get {
				if(ViewState["AC_TreeMenu"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_TreeMenu"];
			}
			set {
				ViewState["AC_TreeMenu"] = value;
			}
		}
		private DataSet dsLingue {
			get {
				if(ViewState["AC_MenuLang"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_MenuLang"];
			}
			set {
				ViewState["AC_MenuLang"] = value;
			}
		}
		
		//private string _SelectedSection; 
		public string SelectedMenuItem
		{
		    get
		    {
//		    	return SelectedSection;
		    	if(base.SelectionMode== null || base.SelectionMode.ToString().ToLower()!="multiple"){
		    		int selectedIndex = this.SelectedIndex;
		    	
			        if (selectedIndex >= 0)
			        {
			            return this.Items[selectedIndex].Value;
			        }
	
					if(ViewState[this.ID + "selectedMenuItem"]!=null)
			        	return ViewState[this.ID + "selectedMenuItem"].ToString();
			        return string.Empty;
		    	} else {
		    		int selectedIndex = this.SelectedIndex;
			        if (selectedIndex >= 0)
			        {
				        string selectedIndexes = string.Empty;
				        for(int i=0;i<this.Items.Count;i++)
				        {
				        	if(this.Items[i].Selected==true)
					        	selectedIndexes += this.Items[i].Value + "|";
				        }
				        if(selectedIndexes.EndsWith("|"))
				        	selectedIndexes = selectedIndexes.Substring(0,selectedIndexes.Length-1);
						return selectedIndexes;
			        }
					if(ViewState[this.ID + "selectedMenuItem"]!=null)
			        	return ViewState[this.ID + "selectedMenuItem"].ToString();
			        return string.Empty;
		    	}
		    }
		    set
		    {
			    if(base.SelectionMode== null || base.SelectionMode.ToString().ToLower()!="multiple"){
		    		bool found = false;
			    	if(this.Items.Count>0) {
			    		for(int i=0;i<this.Items.Count;i++){
			    			if(this.Items[i].Value == value) {
			    				found = true;break;			
			    			}
			    		}
			    	}
					ViewState[this.ID + "selectedMenuItem"] = value;
		    		if(found) {
				    
				        base.SelectedValue = value;
			    	}
		    	} else {
		    		string[] values = value.Split('|');
			    		for(int i=0;i<values.Length;i++){
			    			
					    	if(this.Items.Count>0) {
					    		for(int o=0;i<this.Items.Count;o++){
			    					if(this.Items[o].Value == values[i]) {
					    				this.Items[o].Selected = true;
					    				break;
					    			}
					    		}
						    }
						}
		    		ViewState[this.ID + "selectedMenuItem"] = value;
		    	}
		    }
		}
		
		private void CaricaDati() {
			if(ACM.cmsarea08.Users.CurrentUser.Autorizzato && ACM.cmsarea08.mainconfiguration.MainConf.ModelloLingua != LanguageModel.Single)
				_lingua = Users.CurrentUser.PrefLanguage;
			else
				_lingua = mainconfiguration.MainConf.LinguaPredefinita;
			if(dsMenu==null) {
				if(ACM.cmsarea08.mainconfiguration.MainConf.ModelloLingua == LanguageModel.Single)
					dsMenu = dclass.GetListMenu(_lingua);
				else
					dsMenu = dclass.GetListMenu();
			}
			if(dsMenu==null) {
				this.Items.Clear();
				
			}
			if(dsMenuNames==null) {
				dsMenuNames = dclass.GetMenuNames();
			}
			if(dsMenuNames==null || dsMenuNames.Tables.Count==0 || dsMenuNames.Tables[0].Rows.Count == 0) {
				this.Items.Clear();
				return;
			}
			if(dsLingue==null){
				dsLingue = dclass.GetDropAdminLanguage();
			}
			if(dsLingue==null || dsLingue.Tables.Count==0 || dsLingue.Tables[0].Rows.Count == 0) {
				this.Items.Clear();
				return;
			}
			this.Rows = 1;
			//HttpContext.Current.Response.Write(this.SelectedMenuItem + "<hr>");
			string[] colori = {"#EFFBFF","#FFEFFF","#F6EFFF","#FDFFDF","#e9e9e9","#EFFFF3"};
			int colorcount = 0;
			if(ACM.cmsarea08.mainconfiguration.MainConf.ModelloLingua == LanguageModel.Strict){
				foreach(DataRow dr in dsLingue.Tables[0].Rows){
					if(colorcount==colori.Length)
						colorcount=0;
					
					
					ListItem ito = new ListItem("---" + dr["nome_lingua"].ToString() + " Menu---",dr["cultureinfo"].ToString());
					ito.Attributes.Add("style","background-color:" + colori[colorcount] + ";font-weight:bolder;");
					;
					if(this.Rows<maxsize)
						this.Rows++;
					this.Items.Add(ito);
					this.CostruisciTreeRoot(dr["cultureinfo"].ToString(),colori[colorcount]);
				//	HttpContext.Current.Response.Write(dr["cultureinfo"].ToString() + "  " + colori[colorcount] + "<hr>");
					colorcount++;
				}
			}
			else 
				CostruisciTreeRoot("-1","");
			
			
			/*
			this.DataSource = dsMenu;
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++)
				this.Items.Add(new ListItem(
					dsMenu.Tables[0].Rows[i]["titolo"].ToString(),
					dsMenu.Tables[0].Rows[i]["id"].ToString()));
			if(this.SelectedComponent==string.Empty)
				this.Items[0].Selected=true;
			*/
		
		}
		
		private void CostruisciTreeRoot(string lingua,string colore){
			string filter = lingua=="-1"?"":("lingua_ref = '" + lingua + "' and ");
			//HttpContext.Current.Response.Write(filter);
			foreach(DataRow dr in dsMenuNames.Tables[0].Rows){
				ListItem ito = new ListItem("---" + dr["titolo"].ToString() + "---",dr["id"].ToString()+ "~-1");
				if(SelectedMenuItem.IndexOf(ito.Value) != -1)
					ito.Selected=true;
				if(colore!="")
					ito.Attributes.Add("style","background-color:" + colore + ";");
				if(MostraRoot)
					this.Items.Add(ito);
				
				if(this.Rows<maxsize)
					this.Rows++;
				if(dsMenu!=null){
					
					DataRow[] drlist = dsMenu.Tables[0].Select(filter + "PadreID = -1 and menu_contenitore = "+dr["id"].ToString(),"ordine");
				
					if(drlist.Length!=0){
						for(int i=0;i<drlist.Length;i++){
							CostruisciTree(drlist[i]["id"].ToString(),drlist[i]["titolo"].ToString(),dr["id"].ToString(),0,colore);
						}
					}
				}
			}
		}
		private void CostruisciTree(string id, string titolo, string menu_cont, int ind,string colore){
			string indent = "";
			//for(int o=0;o<ind;o++)
			//	indent+="∙∙∙∙";
			indent = indent.PadLeft(ind*4,'∙');	
			ListItem it_child = new ListItem(indent+"└► "+titolo,menu_cont + "~" + id);

			if(SelectedMenuItem.IndexOf(it_child.Value) != -1 )
				it_child.Selected=true;
			if(colore!="")
				it_child.Attributes.Add("style","background-color:" + colore + ";");
			this.Items.Add(it_child);	
			if(this.Rows<maxsize)
				this.Rows++;
			DataRow[] figli = dsMenu.Tables[0].Select("PadreID = " + id,"ordine");
			//HttpContext.Current.Response.Write("<br>Count voci: " + this.Rows.ToString() + "<br>Figli: "+ figli.Length.ToString() + "<br>" + menu_cont + "~" + id);
			if(figli.Length==0)
				return;
			else{
				ind++;
				for(int i=0;i<figli.Length;i++)
				CostruisciTree(figli[i]["id"].ToString(),figli[i]["titolo"].ToString(),menu_cont,ind,colore);
			}
					
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}

	}
	
	 [DefaultProperty("SelectedRoles")]
    [ToolboxData("<{0}:RolesList runat=server Text=''></{0}:RolesList>")]
	public class RolesList : ListBox{
		
		private string _lingua = null;
		private string _MenuSel = "-1";
		private string _tipomodu = "";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet ds {
			get {
				if(ViewState["AC_RolesList"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_RolesList"];
			}
			set {
				ViewState["AC_RolesList"] = value;
			}
		}
		public bool AllRoles {
			get {
				if(ViewState["AC_RolesListAllRoles"]==null)
					return false;
				else
					return (bool)ViewState["AC_RolesListAllRoles"];
			}
			set {
				ViewState["AC_RolesListAllRoles"] = value;
			}
		}
		public bool AddEveryone {
			get {
				if(ViewState["AC_RolesListAddEveryone"]==null)
					return true;
				else
					return (bool)ViewState["AC_RolesListAddEveryone"];
			}
			set {
				ViewState["AC_RolesListAddEveryone"] = value;
			}
		}
		public bool AddGuest {
			get {
				if(ViewState["AC_RolesListAddGuest"]==null)
					return true;
				else
					return (bool)ViewState["AC_RolesListAddGuest"];
			}
			set {
				ViewState["AC_RolesListAddGuest"] = value;
			}
		}
		public bool AddLoggedin {
			get {
				if(ViewState["AC_AddLoggedin"]==null)
					return true;
				else
					return (bool)ViewState["AC_AddLoggedin"];
			}
			set {
				ViewState["AC_AddLoggedin"] = value;
			}
		}		
		public int maxsize {
			get {
				if(ViewState["AC_RolesListMaxsize"]==null)
					return 10;
				else
					return (int)ViewState["AC_RolesListMaxsize"];
			}
			set {
				ViewState["AC_RolesListMaxsize"] = value;
			}
		}
		public string RolesListType {
			get {
				if(ViewState["AC_RolesListType"]==null)
					return "dropdownlist";
				else
					return ViewState["AC_RolesListType"].ToString();
			}
			set {
				ViewState["AC_RolesListType"] = value;
			}
		}
//		public bool Multiple {
//			get {
//				if(ViewState["AC_TreeMenuMultiple"]==null)
//					return 10;
//				else
//					return (int)ViewState["AC_TreeMenuMultiple"];
//			}
//			set {
//				ViewState["AC_TreeMenuMultiple"] = value;
//			}
//		}
		
	
		
		
		//private string _SelectedSection; 
		public string SelectedItems
		{
		    get
		    {
//		    	return SelectedRoles;
		    	
		    		int selectedIndex = this.SelectedIndex;
			        if (selectedIndex >= 0)
			        {
				        string selectedIndexes = string.Empty;
				        for(int i=0;i<this.Items.Count;i++)
				        {
				        	if(this.Items[i].Selected==true)
					        	selectedIndexes += this.Items[i].Value + "|";
				        }
				        if(selectedIndexes.EndsWith("|"))
				        	selectedIndexes = selectedIndexes.Substring(0,selectedIndexes.Length-1);
						return selectedIndexes;
			        }
					if(ViewState[this.ID + "SelectedRoles"]!=null)
			        	return ViewState[this.ID + "SelectedRoles"].ToString();
			        return "";
		    	
		    }
		    set
		    {
			    	bool selectedyet = false;
		    		string[] values = value.Split('|');
			    		for(int i=0;i<values.Length;i++){
			    			
					    	if(this.Items.Count>0) {
					    		for(int o=0;i<this.Items.Count;o++){
			    					if(this.Items[o].Value == values[i]) {
		    							if(this.SelectionMode == System.Web.UI.WebControls.ListSelectionMode.Multiple || !selectedyet){
		    								this.Items[o].Selected = true;
		    								selectedyet=true;
		    							}break;
					    			}
					    		}
						    }
						}
		    		ViewState[this.ID + "SelectedRoles"] = value;
		    	
		    }
		}
		
		private void CaricaDati() {
			//HttpContext.Current.Response.Write(ACM.cmsarea08.Users.CurrentUser.Role.Score.ToString());
			
			
			if(ACM.cmsarea08.Users.CurrentUser.Autorizzato)
				_lingua = Users.CurrentUser.PrefLanguage;
			else
				_lingua = mainconfiguration.MainConf.LinguaPredefinita;
			if(ds==null) {
				
					ds = dclass.GetRoles(AllRoles);
			}
			if(ds==null || ds.Tables.Count==0 || ds.Tables[0].Rows.Count == 0) {
				this.Items.Clear();
				return;
			}
			this.Rows = 1;
			
			//HttpContext.Current.Response.Write(this.SelectedMenuItem + "<hr>");
		
			CostruisciLista();
			//this.DataBind();
			
			
		}
		
		private void CostruisciLista(){
			bool selectedyet = false;
			ListItem it = null;
			
			if(AddEveryone){
				it = new ListItem("Everyone","everyone");
				if(SelectedItems.IndexOf("everyone"+"|") != -1){
						it.Selected=true;
						selectedyet=true;
				}
				this.Items.Add(it);
			}
			if(AddGuest){
				it = new ListItem("Guests","guest");
				if(SelectedItems.IndexOf("guest"+"|") != -1){
					if(this.SelectionMode == System.Web.UI.WebControls.ListSelectionMode.Multiple || !selectedyet){
						it.Selected=true;
						selectedyet=true;
					}
				
				}
				this.Items.Add(it);	
			}
			if(AddLoggedin){
				it = new ListItem("LoggedIn","loggedin");
				if(SelectedItems.IndexOf("loggedin"+"|") != -1){
					if(this.SelectionMode == System.Web.UI.WebControls.ListSelectionMode.Multiple || !selectedyet){
						it.Selected=true;
						selectedyet=true;
					}
				
				}
				this.Items.Add(it);	
			}			
			
			
			foreach(DataRow dr in ds.Tables[0].Rows){
				ListItem ito = new ListItem(dr["ruolo"].ToString(),dr["ruolo"].ToString());
				
				if(SelectedItems.IndexOf(ito.Value+"|") != -1){
					if(this.SelectionMode == System.Web.UI.WebControls.ListSelectionMode.Multiple || !selectedyet){
						it.Selected=true;
						selectedyet=true;
					}
				}
				this.Items.Add(ito);
				
				if(this.Rows<maxsize)
					this.Rows++;
				
					
//					DataRow[] drlist = dsMenu.Tables[0].Select(filter + "PadreID = -1 and menu_contenitore = "+dr["id"].ToString(),"ordine");
				
					
				}
			}
		
		
		override protected void OnInit(EventArgs e)
		{
			
			if(this.RolesListType.Trim().ToLower()!="listbox"){
				this.maxsize = 1;
				this.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Single;
			}else
				this.SelectionMode= System.Web.UI.WebControls.ListSelectionMode.Multiple;
			
			
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}

	}
	
        [DefaultProperty("SelectedItems")]
    [ToolboxData("<{0}:ContextChooser runat=server></{0}:ContextChooser>")]        
    public class ContextChooser : WebControl {
		
		protected HtmlInputText valore;
//		protected HtmlInputHidden valore;
		protected DropDownList drop;
		protected HtmlSelect selecteds;
		
		private string _layout;
		public ContextChooser():base("fieldset"){ }
		
		public string SelectedItems {
			get {
				if(valore==null)
					valore = new HtmlInputText();
				return this.valore.Value;
			}
			set {
				if(valore==null)
					valore = new HtmlInputText();
				this.valore.Value = value;
			}
		}
	
		override protected void OnInit(EventArgs e)
		{
			
			//drop.ID = this.ID + "sel_Sez";
		
			//valore = new HtmlInputHidden();
			selecteds = new HtmlSelect();
			selecteds.ID = "selitems";
			selecteds.Attributes.Add("size","10");
			drop = new DropDownList();
			drop.ID = "avaitems";
			if(valore==null)
				valore = new HtmlInputText();
			valore.ID = "rightitems";
			// assegna stili grafici agli elementi:
			this.Attributes.Add("style","width:350px;border:1px solid black;clear:both; overflow:auto;");
			this.Attributes.Add("title","ContextChooser");
			valore.Attributes.Add("style","width:165px;clear:both;");
			selecteds.Attributes.Add("style","width:135px;height:235px;");
			drop.Attributes.Add("style","width:165px;");
			
			
			drop.Items.Add(new ListItem("-- scegli --","-1"));
			drop.Items.Add(new ListItem("Moduli","0#"));
			drop.Items.Add(new ListItem("Menu","M#"));
			drop.Items.Add(new ListItem("Voci di Menu","0V#"));
			drop.Items.Add(new ListItem("Sezione","1#S"));
			drop.Items.Add(new ListItem("Categoria","1#C"));
			drop.Items.Add(new ListItem("Articolo","1#A"));
			drop.Items.Add(new ListItem("HomePage","2#"));
			this.Controls.Add(new LiteralControl("<legend>Elementi da Associare</legend>"));
			this.Controls.Add(new LiteralControl("<div style=\"float:left; width:135px;\">"));			
			this.Controls.Add(selecteds);
			this.Controls.Add(new LiteralControl("</div>" +
			                                     "<div style=\"float:left;width:50px;\" id=\"" +this.ClientID +"buttons\">" +
			                                     "<input type=\"button\" value=\"<\" id=\"" +this.ClientID +"addbtm\" style=\"width:46px;margin:0px 2px;\" />" +
			                                     "<input type=\"button\" value=\"x\" id=\"" +this.ClientID +"rembtm\" style=\"width:46px;margin:0px 2px;\" />" +
			                                     "<input type=\"button\" value=\"clear\" id=\"" +this.ClientID +"clearbtm\" style=\"width:46px;margin:0px 2px;\" />" +
			                                     "</div>" +
			                                     "<div style=\"float:right; width:165px;\">"));
			this.Controls.Add(drop);
			this.Controls.Add(new LiteralControl("<div style=\"clear:both;\" id=\"" + this.ClientID + "cntchoices\"></div>"));						
			this.Controls.Add(new LiteralControl("</div>"));									
			this.Controls.Add(new LiteralControl("<div style=\"clear:both;\" id=\"" + this.ClientID + "lng\">" +
			                                     "<ul style=\"display:inline;float:left; width:100px; margin-right:10px;font-size:10px;padding:0px;font-family:Arial;\">" +
			                                     "<li style=\"list-style:none;\"><img src=\"/template/images/spacer.gif\" width=\"10\" height=\"10\" style=\"background:#006600;\"/> Moduli</li>" +
			                                     "<li style=\"list-style:none;\"><img src=\"/template/images/spacer.gif\" width=\"10\" height=\"10\" style=\"background:#990000;\"/> Menu</li>" +
			                                     "<li style=\"list-style:none;\"><img src=\"/template/images/spacer.gif\" width=\"10\" height=\"10\" style=\"background:#CC6600;\"/> voci di Menu</li>" +
			                                     "</ul><ul  style=\"display:inline;float:left; width:100px; margin-right:10px;font-size:10px;padding:0px;font-family:Arial;\">" +
			                                     "<li style=\"list-style:none;\"><img src=\"/template/images/spacer.gif\" width=\"10\" height=\"10\" style=\"background:#FF0000;\"/> Sezione</li>" +
			                                     "<li style=\"list-style:none;\"><img src=\"/template/images/spacer.gif\" width=\"10\" height=\"10\" style=\"background:#FF66CC;\"/> Categoria</li>" +
			                                     "<li style=\"list-style:none;\"><img src=\"/template/images/spacer.gif\" width=\"10\" height=\"10\" style=\"background:#FFCC66;\"/> Articolo</li>" +
			                                     "<li style=\"list-style:none;\"><img src=\"/template/images/spacer.gif\" width=\"10\" height=\"10\" style=\"background:#666666;\"/> HomePage</li>" +
			                                     "</ul></div>"));
			this.Controls.Add(valore);
			this.Controls.Add(new LiteralControl(getJavaScript()));
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
	
		private void Page_Load(object o , EventArgs e) {		
			
			
			//base.OnLoad(e);		
		}
		
		private string getJavaScript() {
			string currentLang = "";
			if(ACM.cmsarea08.Users.CurrentUser.Autorizzato)
				currentLang = Users.CurrentUser.PrefLanguage;
			else
				currentLang = mainconfiguration.MainConf.LinguaPredefinita;
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			sb.Append("<script language=\"javascript\" " +
			          "src=\"/template/plugins/ContextChooser/contextchooserjs.js\"></script>");
			sb.Append("<script language=\"javascript\" >\n");
			sb.Append("	var mioCC = new ContextChooser( ");
			sb.Append("		{panelID:'"+this.ClientID+"',handlerPath:'/administration/core/xml_server.asmx'," +
					          "avaitems:'"+this.drop.ClientID+"', " +
					          "rightitems:'"+this.valore.ClientID+"', " +
							  "selitems:'"+this.selecteds.ClientID+"', " +
					          "currentValue:''}, ");
			sb.Append("		{categorie:'categorie',sezioni:'sezioni'} ");
			sb.Append("		);		");
			sb.Append("</script>");
			return sb.ToString();
		}
		
	}
    
    [DefaultProperty("SelectedLanguage")]
	[ToolboxData("<{0}:DropDownLanguages runat=server Text=''></{0}:DropDownLanguages>")]
	public class DropDownLanguages : DropDownList {
		private string _lingua = null;
		private string _voceSel = "-1";
		private string _tipomodu = "";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private string _memo_test;
		private string _ex_lang ;
		private bool _listitem =false ;
		public string ExcludedLang {
			get {
				return _ex_lang;
			}
			set {
				_ex_lang = value;
				
				this.CaricaDati();
			}
		}
		public string MemoTest {
			get {
				return _memo_test;
			}
			set {
				_memo_test = value;
				
			}
		}
		

		public bool AllListItem {
			get {
				return _listitem;
			}
			set {
				_listitem = value;
			}
		}
		private DataSet dsMenu {
			get {
				if(ViewState["AC_Lingue"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_Lingue"];
			}
			set {
				ViewState["AC_Lingue"] = value;
			}
		}

		public string SelectedLanguage
		{
		    get
		    {
//		    	return SelectedSection;
		        int selectedIndex = this.SelectedIndex;
		        if (selectedIndex >= 0)
		        {
		            return this.Items[selectedIndex].Value;
		        }
		        if(ViewState[this.ID + "selectedlan"]!=null)
		        	return ViewState[this.ID + "selectedlan"].ToString();
		        return string.Empty;
		    }
		    set
		    {
		    	bool found = false;
		    	if(this.Items.Count>0) {
		    		for(int i=0;i<this.Items.Count;i++){
		    			if(this.Items[i].Value == value) {
		    				found = true;break;			
		    			}
		    		}
		    	}
		    	if(found) {
			    	ViewState[this.ID + "selectedlan"] = value;
			        base.SelectedValue = value;
		    	} 	        
		    }
		}
		
		private void CaricaDati() {
			if(dsMenu==null) {
				dsMenu = dclass.GetDropAdminLanguage();
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
//			try {
			this.Items.Clear();
			if(!AllListItem)
				this.Items.Add(new ListItem(" -- ",ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita));
			else
				this.Items.Add(new ListItem(" -- ",string.Join(",",ACM.cmsarea08.mainconfiguration.MainConf.LingueDisponibili))); //all tutte le lingue
			
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++){
				if(_ex_lang != null && _ex_lang.Contains(dsMenu.Tables[0].Rows[i]["cultureinfo"].ToString()))
					continue;
			
				
				this.Items.Add(new ListItem(
					dsMenu.Tables[0].Rows[i]["nome_lingua"].ToString(),
					dsMenu.Tables[0].Rows[i]["cultureinfo"].ToString()));
			}
			if(this.SelectedLanguage==string.Empty)
				this.Items[0].Selected=true;
//			} catch {}
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}
		
		public void MetodoProva(string cicico ) {
			//HttpContext.Current.Response.Write("<hr> funge: " + cicico + "<hr>");
		}
		
		
		public void setCustomParameter(string customp) {
			string[] chiavi_valori = new string[0];
			if(customp.IndexOf('~')==-1)
				return;
			chiavi_valori = customp.Split('~');
			Type typethis = this.GetType();
			for(int i = 0 ; i<chiavi_valori.Length;i++) {
				string xst = "";
				string xsv = "";
				if(chiavi_valori[i].IndexOf('=')==-1)
					continue;
				xst = chiavi_valori[i].Substring(0, chiavi_valori[i].IndexOf('='));
				xsv = chiavi_valori[i].Substring(chiavi_valori[i].IndexOf('=')+1);
				MethodInfo method = typethis.GetMethod(xst.Trim(),BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
				System.Reflection.PropertyInfo membro = typethis.GetProperty(xst,BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
				if(method!=null) {
					method.Invoke(this,new object[] {xsv});
				} else if(membro!=null) {
					membro.SetValue(this,(object)xsv,null);
				} 
			}
		}
		
	}

    [DefaultProperty("SelectedContent")]	
	[ToolboxData("<{0}:SelectContent runat=server Text=''></{0}:SelectContent>")]
	public class SelectContent : WebControl {
		private string _lingua = null;
		private string _voceSel = "-1";
		private string _tipomodu = "";
		private bool _managed = true;
		
		protected DropDownSezioni sezioni;
		protected HtmlSelect categorie;
		protected HtmlSelect articoli;
		protected HtmlInputHidden valore;
//		protected HtmlInputText valore;
		public bool OnlyManaged {
			get {
				return _managed;
			}
			set {
				_managed=value;
			}
		}

		public string SelectedContent
		{
		    get
		    {
				string alp = valore.Value.Replace("[","");
				alp = alp.Replace("\'","");
				alp = alp.Replace(",","~");
				alp = alp.Replace("]","");
				return alp;
		    }
		    set
		    {
				if(value.IndexOf("~")!=-1) {
					string[] s = value.Split('~');
					if(s.Length>=3) {
						sezioni.SelectedSection =s[0] ;
						valore.Value = "['" + s[0] + "','" + s[1] + "','" + s[2] + "']";
					}
				} else {
					if(value.Trim()!="") {
						sezioni.SelectedSection =value;
						valore.Value = "['" + value + "']";
					}
				}
		    }
		}
		
		override protected void OnInit(EventArgs e)
		{
			sezioni = new DropDownSezioni();
			sezioni.OnlyManaged = this.OnlyManaged;
			sezioni.ID = this.ID + "sel_Sez";
			categorie = new HtmlSelect();
			categorie.ID = this.ID + "sel_cat";
			articoli = new HtmlSelect();
			articoli.Attributes.Add("size","10");
			articoli.ID = this.ID + "sel_cont";
			categorie.Style.Add("display","none");
			
//			valore = new HtmlInputText();
			valore = new HtmlInputHidden();
			valore.ID = this.ID + "sel_hid";
			this.Controls.Add(new LiteralControl("<table><tr><td valign=\"top\">"));
			this.Controls.Add(sezioni);
			this.Controls.Add(categorie);
			this.Controls.Add(new LiteralControl("</td><td valign=\"top\">"));
			this.Controls.Add(articoli);
			this.Controls.Add(valore);
			this.Controls.Add(new LiteralControl("</td></tr></table>"));
			this.Controls.Add(new LiteralControl(getJavaScript()));
			InitializeComponent();
			base.OnInit(e);			
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		private string getJavaScript() {
			string currentLang = "";
			if(ACM.cmsarea08.Users.CurrentUser.Autorizzato)
				currentLang = Users.CurrentUser.PrefLanguage;
			else
				currentLang = mainconfiguration.MainConf.LinguaPredefinita;
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			sb.Append("<script language=\"javascript\" type=\"text/javascript\">\n<!--\n");
			sb.Append("var xml_" + this.ClientID + ";");
			sb.Append("var xml2_" + this.ClientID + ";");
			
			sb.Append("function InitMe" + this.ID + "() {");
			sb.Append("var cont = document.getElementById('" +this.ClientID + "');");
			sb.Append("if(cont==null) return; ");
			sb.Append("var opsel = cont.getElementsByTagName('select');");
			sb.Append("var regSEZ = new RegExp(\"sel_Sez$\");");
			sb.Append("var regCAT = new RegExp(\"sel_cat$\");");
			sb.Append("var regCOT = new RegExp(\"sel_cont$\");");
			sb.Append(" InitCategory" +this.ID+ "(); ");
			sb.Append(" InitContent" +this.ID+ "(); ");
			sb.Append("for(var i=0;i<opsel.length;i++) { ");
			sb.Append(" if(regSEZ.test(opsel[i].getAttribute('id') ) ) ");
			sb.Append("   opsel[i].onchange=SelectedSEZ" +this.ID+ ";");
			sb.Append(" if(regCAT.test(opsel[i].getAttribute('id') ) ) ");
			sb.Append("   opsel[i].onchange=SelectedCAT" +this.ID+ ";");
			sb.Append(" if(regCOT.test(opsel[i].getAttribute('id') ) ) ");
			sb.Append("   opsel[i].onchange=SelectedCOT" +this.ID+ ";");
			sb.Append("}");
			sb.Append("} ");
			sb.Append("function SelectedSEZ" +this.ID+ "(e) { ");
			sb.Append("e = e || event; ");
			sb.Append("var obj = e.target || e.srcElement; ");
			sb.Append("var valCont = document.getElementById('" + valore.ClientID + "');");
			//cerca il controllo VALORE E INSERISCI LA SCELTA POI CHIAMA FUNZ CATEGO_INIT();
			sb.Append("if(valCont!=null)");
			sb.Append("valCont.value = '[\\'' + obj.value + '\\']';");
			sb.Append("InitCategory" + this.ID + "();");
			sb.Append("ResetArticle" +this.ClientID+ "();");
			sb.Append("valCont=null;");
			sb.Append("}");
			sb.Append("function SelectedCAT" +this.ID+ "(e) { ");
			sb.Append("e = e || event; ");
			sb.Append("var obj = e.target || e.srcElement; ");
			//ottieni l'arrya e push il nuovo valore.
			sb.Append("var valVal = document.getElementById('" + valore.ClientID + "');");
			sb.Append("if (valVal==null) return;");
			sb.Append("var valori = eval(valVal.value);");
			
			sb.Append(" valVal.value ='';");
			sb.Append("if(valori.length>0) { ");
			sb.Append(" for(var vj =0;vj<(valori.length>1?1:valori.length);vj++) ");
			sb.Append("    valVal.value+='\\'' + valori[vj] + '\\',';");
			sb.Append(" }");
			sb.Append("if(obj.value!='-1') ");
			sb.Append(" valVal.value = valVal.value + '\\'' + obj.value + '\\',';");
			sb.Append("if(valVal.value.lastIndexOf(',')!=-1) valVal.value=valVal.value.substr(0,valVal.value.length-1); ");
			sb.Append(" valVal.value = '[' + valVal.value + ']';");
			sb.Append(" valVal = null; ");
			sb.Append("InitContent" +this.ID+ "();");
			
			sb.Append("}");
			
			sb.Append("function SelectedCOT" +this.ID+ "(e) { ");
			sb.Append("e = e || event; ");
			sb.Append("var obj = e.target || e.srcElement; ");
			sb.Append("var valVal = document.getElementById('" + valore.ClientID + "');");
			sb.Append("if (valVal==null) return;");
			sb.Append("var valori = eval(valVal.value);");
			sb.Append(" valVal.value ='';");
			sb.Append("if(valori.length>0) { ");
			sb.Append(" for(var vj =0;vj<(valori.length>2?2:valori.length);vj++) ");
			sb.Append("    valVal.value+='\\'' + valori[vj] + '\\',';");
			sb.Append(" }");
			sb.Append("if(obj.value!='-1') ");
			sb.Append(" valVal.value = valVal.value + '\\'' + obj.value + '\\',';");
			sb.Append("if(valVal.value.lastIndexOf(',')!=-1) valVal.value=valVal.value.substr(0,valVal.value.length-1); ");
			sb.Append(" valVal.value = '[' + valVal.value + ']';");
			sb.Append(" valVal = null; ");
			sb.Append("}");
			
			sb.Append("function InitCategory" +this.ID+ "() { ");
			sb.Append("var valVal = document.getElementById('" + valore.ClientID + "');");
			sb.Append("var valor;");
			sb.Append("if (valVal==null) return;");
			sb.Append(" if(valVal.value=='') return; ");
			sb.Append(" valor = eval(valVal.value);");
			sb.Append(" if(valor==null) return; ");
			sb.Append("if (valor.length>0) {");
			sb.Append(" ResetCateg" +this.ClientID+ "(); if(valor[0]=='-1') { ResetCateg" +this.ClientID+ "();return; }");
			//dentro l'if
			sb.Append(" else CaricaXML" + this.ID + "('/administration/Core/xml_server.asmx/getCategoriesbySec?lingua="+currentLang+"&sezione=' + valor[0]+'&managed="+this.OnlyManaged+"');");
			sb.Append("} valVal = null;");
			sb.Append("}");
			//carica articoli
			sb.Append("function InitContent" +this.ID+ "() { ");
			sb.Append("var valVal = document.getElementById('" + valore.ClientID + "');");
			sb.Append("var valor;");
//			sb.Append("alert('qui ci sono');");
			
			sb.Append("if (valVal==null) return;");
			sb.Append(" if(valVal.value=='') return; ");
//			sb.Append("alert('valori: ' + valVal.value);");
			
			sb.Append(" valor = eval(valVal.value);");
			sb.Append(" if(valor==null) return; ");
//			sb.Append("alert('leng: ' + valor.length);");
			
			sb.Append("if (valor.length>=2) {");
//			sb.Append("alert('parto' + valor[1]);");
			sb.Append(" ResetArticle" +this.ClientID+ "(); " +
			          " if(valor[1]=='-1') { ResetArticle" +this.ClientID+ "();return; }");
			//dentro l'if //+'&managed="+this.OnlyManaged+"'
			sb.Append(" else   " +
			          "" +
			          "CaricaXML2" + this.ID + "('/administration/Core/xml_server.asmx/getContentssbySecCat?lingua="+currentLang+"&sezione=' + valor[0]" +
			          "+'&categoria=' + valor[1]+'&managed="+this.OnlyManaged+"');");
			sb.Append("} valVal = null;");
			sb.Append("}");			
			//funzione apri xml 1
			sb.Append("\nfunction CaricaXML" + this.ID + "(url) { \n");
			sb.Append(" xml_" + this.ClientID + "=null; \n");
			//sb.Append(" alert(url); ");
			sb.Append("if (window.XMLHttpRequest) xml_" + this.ClientID + "=new XMLHttpRequest(); \n");
			sb.Append("else if (window.ActiveXObject) xml_" + this.ClientID + "=new ActiveXObject(\"Microsoft.XMLHTTP\");\n");
			sb.Append("if (xml_" + this.ClientID + "!=null) { \n");
			sb.Append("	xml_" + this.ClientID + ".onreadystatechange=XmlReady"+this.ClientID+"; \n");
			sb.Append(" xml_" + this.ClientID + ".open(\"GET\",url,true); \n");
			sb.Append(" xml_" + this.ClientID + ".send(null); \n");
			sb.Append(" } else alert('No Xml support.'); \n");
			sb.Append("} \n");
			sb.Append("function XmlReady"+this.ClientID+"() { \n");
			sb.Append(" if (xml_" + this.ClientID + ".readyState==4) { \n");
			sb.Append(" if (xml_" + this.ClientID + ".status==200) { \n");
			sb.Append(" if( xml_" + this.ClientID + ".responseText == null) { ");
			sb.Append(" ResetCateg" +this.ClientID+ "(); alert('no dati'); return; }");
			
			sb.Append(" else { ");
			//carica valori nel controllo.
			sb.Append(" var dati = xml_" + this.ClientID + ".responseXML.getElementsByTagName(\"Table\");");
			sb.Append(" var valCat =document.getElementById('" + categorie.ClientID + "');");
			sb.Append(" var valVal =document.getElementById('" + valore.ClientID + "');");
			sb.Append(" var valorie;if(valVal!=null) valorie = eval(valVal.value);");
			sb.Append(" if( valCat==null) return; ");
			sb.Append(" if(dati.length>0) { ");
			sb.Append(" valCat.style.display='block';");
			sb.Append(" valCat.options[valCat.options.length] =new Option('--','-1');");
			sb.Append(" } else ResetCateg" +this.ClientID+ "(); ");
			sb.Append(" for( var i=0; i<dati.length; i++ ) { \n");
			sb.Append(" valCat.options[valCat.options.length] =new Option( XMLItem" +this.ClientID+ "(dati[i],'titolo')," +
			          "XMLItem" +this.ClientID+ "(dati[i],'id'));");
			sb.Append("if(valorie!=null && valorie.length>=1) {" +
			          "	if(valCat.options[valCat.options.length-1].value==valorie[1]) " +
			          "		valCat.options[valCat.options.length-1].selected=true;" +
			          "}");
			sb.Append(" \n} ");
			sb.Append(" } ");
			sb.Append(" } else { ResetCateg" +this.ClientID+ "();alert('Errore Reading XML');}  } \n");
			sb.Append("}\n");
			//leggi elemento xml 
			sb.Append(" function XMLItem" +this.ClientID+ "(itemxml,xmltag) { ");
			sb.Append(" var tmpElement = null; ");
			sb.Append(" tmpElement = itemxml.getElementsByTagName(xmltag)[0]; ");
			sb.Append(" if (tmpElement != null) {" +
			          " return unescape(tmpElement.childNodes[0].nodeValue); } ");
			sb.Append(" return 'vuoto'");
			sb.Append("}\n");
			
			//funzione apri xml 2
			sb.Append("\nfunction CaricaXML2" + this.ID + "(url) { \n");
			sb.Append(" xml2_" + this.ClientID + "=null; \n");
//			sb.Append(" alert(url); ");
			sb.Append("if (window.XMLHttpRequest) xml2_" + this.ClientID + "=new XMLHttpRequest(); \n");
			sb.Append("else if (window.ActiveXObject) xml2_" + this.ClientID + "=new ActiveXObject(\"Microsoft.XMLHTTP\");\n");
			sb.Append("if (xml2_" + this.ClientID + "!=null) { \n");
			sb.Append("	xml2_" + this.ClientID + ".onreadystatechange=XmlReady2"+this.ClientID+"; \n");
			sb.Append(" xml2_" + this.ClientID + ".open(\"GET\",url,true); \n");
			sb.Append(" xml2_" + this.ClientID + ".send(null); \n");
			sb.Append(" } else alert('No Xml support.'); \n");
			sb.Append("} \n");
			
			sb.Append("function XmlReady2"+this.ClientID+"() { \n");
			sb.Append(" if (xml2_" + this.ClientID + ".readyState==4) { \n");
			sb.Append(" if (xml2_" + this.ClientID + ".status==200) { \n");
			sb.Append(" if( xml2_" + this.ClientID + ".responseText == null) { ");
			sb.Append(" ResetArticle" +this.ClientID+ "(); alert('no dati'); return; }");
			sb.Append(" else { ");
			//carica valori nel controllo.
			sb.Append(" var dati = xml2_" + this.ClientID + ".responseXML.getElementsByTagName(\"Table\");");
			sb.Append(" var valCat =document.getElementById('" + articoli.ClientID + "');");
			sb.Append(" var valVal =document.getElementById('" + valore.ClientID + "');");
			sb.Append(" var valorie;if(valVal!=null) valorie = eval(valVal.value);");
			sb.Append(" if( valCat==null) return; ");
			sb.Append(" if(dati.length>0) { ");
			sb.Append(" valCat.style.display='block';");
			//sb.Append(" valCat.options[valCat.options.length] =new Option('--','-1');");
			sb.Append(" } else ResetArticle" +this.ClientID+ "(); ");
			sb.Append(" for( var i=0; i<dati.length; i++ ) { \n");
			sb.Append(" valCat.options[valCat.options.length] =new Option( XMLItem" +this.ClientID+ "(dati[i],'titolo')," +
			          "XMLItem" +this.ClientID+ "(dati[i],'id'));");
			sb.Append("if(valorie!=null && valorie.length>=2) {" +
			          "	if(valCat.options[valCat.options.length-1].value==valorie[2] ) " +
			          "		valCat.options[valCat.options.length-1].selected=true;" +
			          "}");
			sb.Append(" \n} ");
			sb.Append(" } ");
			sb.Append(" } else { ResetArticle" +this.ClientID+ "();alert('Errore Reading XML');}  } \n");
			
			
			sb.Append("}\n");
			//leggi elemento xml 
//			sb.Append(" function XMLItem2" +this.ClientID+ "(itemxml,xmltag) { ");
//			sb.Append(" var tmpElement = null; ");
//			sb.Append(" tmpElement = itemxml.getElementsByTagName(xmltag)[0]; ");
//			sb.Append(" if (tmpElement != null) return tmpElement.childNodes[0].nodeValue; ");
//			sb.Append(" return 'vuoto'");
//			sb.Append("}\n");
			
			//function resetta WAITING 
			sb.Append(" function ResetAll" +this.ClientID+ "() { ");

			sb.Append("}\n");
			//function resetta Categorie
			sb.Append(" function ResetCateg" +this.ClientID+ "() { ");
			sb.Append("var valCat = document.getElementById('" + categorie.ClientID + "');");
			sb.Append("if (valCat==null) return;");
			sb.Append("while(valCat.length>0) ");
			sb.Append("		valCat.remove(valCat.length-1);");
			sb.Append("valCat.style.display='none';");
			sb.Append("valCat=null;");
			sb.Append("}\n");
			//function resetta Articoli
			sb.Append(" function ResetArticle" +this.ClientID+ "() { ");
			sb.Append("var valCat = document.getElementById('" + articoli.ClientID + "');");
			sb.Append("if (valCat==null) return;");
			sb.Append("while(valCat.length>0) ");
			sb.Append("		valCat.remove(valCat.length-1);");
			sb.Append("valCat=null;");
			sb.Append("}\n");	
			
			sb.Append("InitMe" + this.ID + "();");
			sb.Append("\n//-->\n</script>");
			return sb.ToString();
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}

	}

    [DefaultProperty("SelectedComponent")]	
	[ToolboxData("<{0}:DropDownComponents runat=server ></{0}:DropDownComponents>")]
	public class DropDownComponents : DropDownList {
		private string _lingua = null;
		private string _voceSel = "-1";
		private string _tipomodu = "";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet dsMenu {
			get {
				if(ViewState["AC_Modules"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_Modules"];
			}
			set {
				ViewState["AC_Modules"] = value;
			}
		}

		public string IsMenu {
			get {
				return _tipomodu;
			}
			set {
				_tipomodu=value;
			}
			
		}
		//private string _SelectedSection; 
		public string SelectedComponent
		{
		    get
		    {
//		    	return SelectedSection;
		        int selectedIndex = this.SelectedIndex;
		        if (selectedIndex >= 0)
		        {
		            return this.Items[selectedIndex].Value;
		        }
		        if(ViewState[this.ID + "selectedmod"]!=null)
		        	return ViewState[this.ID + "selectedmod"].ToString();
		        return string.Empty;
		    }
		    set
		    {
		    	bool found = false;
		    	if(this.Items.Count>0) {
		    		for(int i=0;i<this.Items.Count;i++){
		    			if(this.Items[i].Value == value) {
		    				found = true;break;			
		    			}
		    		}
		    	}
		    	if(found) {
			    	ViewState[this.ID + "selectedmod"] = value;
			        base.SelectedValue = value;
		    	} 	        
		    }
		}
		
		private void CaricaDati() {
			if(dsMenu==null) {
				dsMenu = dclass.GetDropAdminComponents(_tipomodu);
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
			this.Items.Add(new ListItem(" -- ","-1"));
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++)
				this.Items.Add(new ListItem(
					dsMenu.Tables[0].Rows[i]["titolo"].ToString(),
					dsMenu.Tables[0].Rows[i]["id"].ToString()));
			if(this.SelectedComponent==string.Empty)
				this.Items[0].Selected=true;
			
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}

	}
	 [DefaultProperty("Selections")]
    [ToolboxData("<{0}:CustomList runat=server ></{0}:CustomList>")]
	public class CustomList : ListBox{
		
		
		private string _selections = "";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet ds {
			get {
				if(ViewState["AC_CustomList"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_CustomList"];
			}
			set {
				ViewState["AC_CustomList"] = value;
			}
		}
		
		public int maxsize {
			get {
				if(ViewState["AC_CustomListMaxsize"]==null)
					return 10;
				else
					return (int)ViewState["AC_CustomListMaxsize"];
			}
			set {
				ViewState["AC_CustomListMaxsize"] = value;
			}
		}
		public string Sql {
			get {
				if(ViewState["AC_CustomListSql"]==null)
					return "dropdownlist";
				else
					return ViewState["AC_CustomListSql"].ToString();
			}
			set {
				ViewState["AC_CustomListSql"] = value;
			}
		}
		public string TextColumn {
			get {
				if(ViewState["AC_CustomListTextColumn"]==null)
					return "titolo";
				else
					return ViewState["AC_CustomListTextColumn"].ToString();
			}
			set {
				ViewState["AC_CustomListTextColumn"] = value;
			}
		}
		public string ValueColumn {
			get {
				if(ViewState["AC_CustomListValueColumn"]==null)
					return "id";
				else
					return ViewState["AC_CustomListValueColumn"].ToString();
			}
			set {
				ViewState["AC_CustomListValueColumn"] = value;
			}
		}
		public string TablePrefixReplace {
			get {
				if(ViewState["AC_CustomListTablePrefixReplace"]==null)
					return string.Empty;
				else
					return ViewState["AC_CustomListTablePrefixReplace"].ToString();
			}
			set {
				ViewState["AC_CustomListTablePrefixReplace"] = value;
			}
		}

		
	
		
		
		//private string _SelectedSection; 
		public string Selections
		{
		    get
		    {

		    	
		    		int selectedIndex = this.SelectedIndex;
			        if (selectedIndex >= 0)
			        {
				        string selectedIndexes = string.Empty;
				        for(int i=0;i<this.Items.Count;i++)
				        {
				        	if(this.Items[i].Selected==true)
					        	selectedIndexes += this.Items[i].Value + "|";
				        }
				        if(selectedIndexes.EndsWith("|"))
				        	selectedIndexes = selectedIndexes.Substring(0,selectedIndexes.Length-1);
						return selectedIndexes;
			        }
					if(ViewState[this.ID + "CustomListSelections"]!=null)
			        	return ViewState[this.ID + "CustomListSelections"].ToString();
			        return "";
		    	
		    }
		    set
		    {
			    	bool selectedyet = false;
		    		string[] values = value.Split('|');
			    		for(int i=0;i<values.Length;i++){
					    	//if(this.Items.Count>0) {
		    				
					    		for(int o=0;o<this.Items.Count;o++){
			    					
		    						if(this.Items[o].Value == values[i]) {
		    							if(this.SelectionMode == System.Web.UI.WebControls.ListSelectionMode.Multiple || !selectedyet){
		    								this.Items[o].Selected = true;
		    								selectedyet=true;
		    							}break;
					    			}
					    		}
						    //}
						}
		    		ViewState[this.ID + "CustomListSelections"] = value;
		    	
		    }
		}
		
		private void CaricaDati() {
			
		
			
			if(ds==null) {
				if(!string.IsNullOrEmpty(TablePrefixReplace))
					Sql = Sql.Replace(TablePrefixReplace,dclass.TablePrefix);
				ds = dclass.ExecuteDataset(Sql);
			}
			
			this.Rows = 1;
			if(ds==null || ds.Tables.Count==0 || ds.Tables[0].Rows.Count == 0 || !ds.Tables[0].Columns.Contains(ValueColumn) ||
			    !ds.Tables[0].Columns.Contains(TextColumn)) {
				this.Items.Clear();
				return;
			}
			
			
			
		
			CostruisciLista();
			//this.DataBind();
			
			
		}
		
		private void CostruisciLista(){
			if(!Selections.EndsWith("|"))
				Selections = Selections+"|";
			bool selectedyet = false;
			_selections = Selections;
			
			ListItem ito = 	new ListItem("--","");
			this.Items.Add(ito);
			
			foreach(DataRow dr in ds.Tables[0].Rows){
				ito = new ListItem(HttpUtility.HtmlDecode(dr[TextColumn].ToString()),dr[ValueColumn].ToString());
				if(_selections.IndexOf(ito.Value+"|") != -1 && (this.SelectionMode == System.Web.UI.WebControls.ListSelectionMode.Multiple || !selectedyet)){
					
					
					ito.Selected=true;
					selectedyet=true;
					
				}
				this.Items.Add(ito);
				
				if(this.Rows<maxsize)
					this.Rows++;
				
					
				
					
				}
			}
		
		
		override protected void OnInit(EventArgs e)
		{
	
			InitializeComponent();
			base.OnInit(e);
			if(string.IsNullOrEmpty(Sql))
				return;
			
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}

	}
	
	 [DefaultProperty("SelectedModules")]	
	[ToolboxData("<{0}:ModulesListBox runat=server ></{0}:ModulesListBox>")]
	public class ModulesListBox : ListBox {
		private string _lingua = null;
		private string _voceSel = "-1";
		private string _tipomodu = "";
		private bool _onlysearcheable;
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet dsMenu {
			get {
				if(ViewState["ComponentListBox"]==null)
					return null;
				else
					return (DataSet)ViewState["ComponentListBox"];
			}
			set {
				ViewState["ComponentListBox"] = value;
			}
		}
		public bool OnlySearcheable {
			get {
				return _onlysearcheable;
			}
			set {
				_onlysearcheable=value;
			}
			
		}
		public string IsMenu {
			get {
				return _tipomodu;
			}
			set {
				_tipomodu=value;
			}
			
		}
		//private string _SelectedSection; 
		public string SelectedModules
		{
		    get
		    {
//		    	return SelectedRoles;
		    	
		    		int selectedIndex = this.SelectedIndex;
			        if (selectedIndex >= 0)
			        {
				        if(ViewState[this.ID + "SelectedModules"]!=null)
			        		return ViewState[this.ID + "SelectedModules"].ToString();
			        
			        	string selectedIndexes = string.Empty;
				        
				        for(int i=0;i<this.Items.Count;i++)
				        {
				        	if(this.Items[i].Selected==true)
					        	selectedIndexes += this.Items[i].Value + "|";
				        }
				        if(selectedIndexes.EndsWith("|"))
				        	selectedIndexes = selectedIndexes.Substring(0,selectedIndexes.Length-1);
						return selectedIndexes;
			        }
						return string.Empty;
		    	
		    }
		    set
		    {
			    
		    		string[] values = value.Split('|');
			    		for(int i=0;i<values.Length;i++){
			    			
					    	if(this.Items.Count>0) {
					    		for(int o=0;i<this.Items.Count;o++){
			    					if(this.Items[o].Value == values[i]) {
					    				this.Items[o].Selected = true;
					    				break;
					    			}
					    		}
						    }
						}
		    		ViewState[this.ID + "SelectedModules"] = value;
		    	
		    }
		}
		const string Query = "select modu.id,modu.titolo from {0}moduli as modu left join {0}componenti as comp on comp.id=modu.id_componente {1};";
		private void CaricaDati() {
			if(dsMenu==null) {
				dsMenu = dclass.ExecuteDataset(string.Format(Query,dclass.TablePrefix,(this.OnlySearcheable?"where issearch='1' and iscontentargs='0' and campi_table<>'' and ref_table<>''":"")));
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
			
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++){
				ListItem ito = new ListItem(
					dsMenu.Tables[0].Rows[i]["titolo"].ToString(),
					dsMenu.Tables[0].Rows[i]["id"].ToString());
				this.Items.Add(ito);
				if(SelectedModules.IndexOf(ito.Value) != -1)
					ito.Selected=true;
			}
			//this.SelectionMode= System.Web.UI.WebControls.ListSelectionMode.Multiple;
			
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}

	}
	
    [DefaultProperty("SelectedTimeZone")]	
	[ToolboxData("<{0}:SelectTimeZone runat=server Text=''></{0}:SelectTimeZone>")]
	public class SelectTimeZone : DropDownList {
		private string _lingua = null;
		private string _voceSel = "-1";
		private string _tipomodu = "";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet dsMenu {
			get {
				if(ViewState["AC_TimeZone"]==null)
					return null;
				else
					return (DataSet)ViewState["AC_TimeZone"];
			}
			set {
				ViewState["AC_TimeZone"] = value;
			}
		}

		//private string _SelectedSection; 
		public string SelectedTimeZone
		{
		    get
		    {
//		    	return SelectedSection;
		        int selectedIndex = this.SelectedIndex;
		        if (selectedIndex >= 0)
		        {
		            return this.Items[selectedIndex].Value;
		        }
		        if(ViewState[this.ID + "selectedtz"]!=null)
		        	return ViewState[this.ID + "selectedtz"].ToString();
		        return string.Empty;
		    }
		    set
		    {
		    	bool found = false;
		    	if(this.Items.Count>0) {
		    		for(int i=0;i<this.Items.Count;i++){
		    			if(this.Items[i].Value == value.ToString().Replace("+","")) {
		    				found = true;break;			
		    			}
		    		}
		    	}
		    	if(found) {
			    	ViewState[this.ID + "selectedmod"] = value.ToString().Replace("+","");
			        base.SelectedValue = value.ToString().Replace("+","");
		    	} 	        
		    }
		}
		
		private void CaricaDati() {
			if(dsMenu==null) {
				dsMenu = dclass.GetAdminTimeZones();
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
			this.Items.Add(new ListItem(" -- ","-1"));
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++)
				this.Items.Add(new ListItem(
					dsMenu.Tables[0].Rows[i]["meta_desc"].ToString(),
					dsMenu.Tables[0].Rows[i]["time_id"].ToString()));
			if(this.SelectedTimeZone==string.Empty)
				this.Items[0].Selected=true;
			
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}

	}

    [DefaultProperty("Color")]	
	[ToolboxData("<{0}:ColorPicker runat=server Text=''></{0}:ColorPicker>")]
	public class ColorPicker : WebControl {
		private string _color = "";
//		private string colorcode = "";
		
		private HtmlInputText hi = new HtmlInputText();
		public string Color
		{
		    get
		    {
		        
		    	if(ViewState[this.ID + "colorpicker"]!=null){
		    		if(hi.Value==""){
		        		hi.Value = ViewState[this.ID + "colorpicker"].ToString();
		    		}
		    			return hi.Value;
		    		
		    	}
		        else
		        	return hi.Value;
		        
		    }
		    set
		    {
		    	hi.Value = value;
		    	ViewState[this.ID + "colorpicker"] = hi.Value;
			        
		    	 	        
		    }
		}
		
		private void CaricaDati() {
			
			
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			HtmlGenericControl csslink = (HtmlGenericControl)this.Page.Header.FindControl("csscolorpicker");
			if(csslink==null){
				csslink = new HtmlGenericControl("link");
				csslink.Attributes.Add("href","/administration/template/colorpicker/css/colorPicker.css");
				csslink.ID = "csscolorpicker";
				csslink.Attributes.Add("rel","stylesheet");
				csslink.Attributes.Add("type","text/css");
				this.Page.Header.Controls.Add(csslink);
			}
			HtmlGenericControl jslink = (HtmlGenericControl)this.Page.Header.FindControl("jscolorpicker");
			if(jslink==null){
				jslink = new HtmlGenericControl("script");
				jslink.ID = "jscolorpicker";
				jslink.Attributes.Add("type","text/javascript");
				jslink.Attributes.Add("language","javascript");
				jslink.Attributes.Add("src","/administration/template/colorpicker/js/colorPicker.js");
				this.Page.Header.Controls.Add(jslink);
			}
			
			hi.ID = this.ID + "color";
			hi.Attributes.Add("OnClick","startColorPicker(this)");
			hi.Attributes.Add("runat","server");
			//hi.Value = _color;
			hi.Attributes.Add("type","text");
			this.Controls.Add(hi);
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
			
		}

	}


	
    [DefaultProperty("SelectedComponent")]	
	[ToolboxData("<{0}:ChooseComponentInstance runat=server ></{0}:ChooseComponentInstance>")]
	public class ChooseComponentInstance : DropDownList {
		private string _lingua = null;
		private string _voceSel = "-1";
		private string _tipomodu = "";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private DataSet dsMenu {
			get {
				if(ViewState["AC_Modules" + this.ID]==null)
					return null;
				else
					return (DataSet)ViewState["AC_Modules" + this.ID];
			}
			set {
				ViewState["AC_Modules" + this.ID] = value;
			}
		}

		public string SelectedComponent
		{
		    get
		    {
//		    	return SelectedSection;
		        int selectedIndex = this.SelectedIndex;
		        if (selectedIndex >= 0)
		        {
		            return this.Items[selectedIndex].Value;
		        }
		        if(ViewState[this.ID + "selectedmod"]!=null)
		        	return ViewState[this.ID + "selectedmod"].ToString();
		        return string.Empty;
		    }
		    set
		    {
		    	bool found = false;
		    	if(this.Items.Count>0) {
		    		for(int i=0;i<this.Items.Count;i++){
		    			if(this.Items[i].Value == value) {
		    				found = true;break;			
		    			}
		    		}
		    	}
		    	if(found) {
			    	ViewState[this.ID + "selectedmod"] = value;
			        base.SelectedValue = value;
		    	} 	        
		    }
		}
		
		public string FilterComponent {
			get {
		        if(ViewState[this.ID + "filterby"]!=null)
		        	return ViewState[this.ID + "filterby"].ToString();
		        return string.Empty;				
			}
			set {
				string currentva = "";
		        if(ViewState[this.ID + "filterby"]!=null)
		        	currentva =  ViewState[this.ID + "filterby"].ToString();
		        if(currentva!=value) {
		        	dsMenu=null;
		        }
		        ViewState[this.ID + "filterby"] = value;
		        CaricaDati();
			}
		}
		
		private void CaricaDati() {
			if(dsMenu==null) {
				if(this.FilterComponent.Trim().Length>0) 
					dsMenu = dclass.GetDropAdminComponentsInstance(this.FilterComponent);
				else
					dsMenu = dclass.GetDropAdminComponentsInstance();
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
			this.Items.Clear();
			this.Items.Add(new ListItem(" -- ","-1"));
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++)
				this.Items.Add(new ListItem(
					dsMenu.Tables[0].Rows[i]["titolo"].ToString(),
					dsMenu.Tables[0].Rows[i]["id"].ToString()));
			if(this.SelectedComponent==string.Empty)
				this.Items[0].Selected=true;
			
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			CaricaDati();
		}

		private void InitializeComponent()
		{
			
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
		}

	}
	
	
    [DefaultProperty("TitleConfiguration")]	
	[ToolboxData("<{0}:TitleManager runat=server ></{0}:TitleManager>")]
	public class TitleManager : WebControl {
		private string _tc = "";
		
		private CheckBox checker = new CheckBox();
		private DropDownList tags = new DropDownList();
		private TextBox title = new TextBox();
		
		//private Label ltag = new Label();
		//private Label lcheck = new Label();

		
		public string TitleConfiguration {
			get {
				string valore = "";
				if(!checker.Checked) return string.Empty;
				if(tags.SelectedIndex == -1) return string.Empty;
				if(title.Text.Trim()=="") return string.Empty;
				valore = HttpUtility.HtmlEncode(title.Text.Trim().Replace("~"," "));
				valore += "~" + tags.SelectedValue;
				valore += "~" + checker.Checked.ToString();
				return valore;				
			}
			set {
				string[] valore = new string[0];
				if(value==null) return;
				if(value==string.Empty) return;
				if(value.Trim().Length==0) return;
				if(value.Trim().IndexOf('~')==-1) return;
				valore = value.Trim().Split('~');
				if(valore.Length<3) return ;
				title.Text = HttpUtility.HtmlDecode(valore[0]);
				tags.SelectedValue  = valore[1];
				checker.Checked = (valore[2].ToLower()=="true"?true:false);
			}
			
		}
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			
		}

		private void InitializeComponent()
		{	
			this.Controls.Add(title);
			this.Controls.Add(new LiteralControl("<br class=\"clearbr\" />"));
			this.Controls.Add(checker);
			this.Controls.Add(new LiteralControl("<br class=\"clearbr\" />"));
			this.Controls.Add(tags);
			//this.Controls.Add(ltag);
			this.Controls.AddAt(2,new LiteralControl("<label for=\""+checker.ClientID+"\">Mostra Titolo</label>"));
			this.Controls.AddAt(5,new LiteralControl("<label for=\""+tags.ClientID+"\">Tipo HTML</label>"));
			
//			this.ltag.AssociatedControl= this.tags;
//			this.lcheck.AssociatedControl = this.checker;
//			this.ltag.Text = "Tipo HTML:";
//			this.lcheck.Text = "Mostra Titolo:";
			//
			this.tags.Items.Clear();
			this.tags.Items.Add(new ListItem("div","div"));
			this.tags.Items.Add(new ListItem("span","span"));
			for(int i=1; i<7;i++)
				this.tags.Items.Add(new ListItem("h" +i,"h" +i));
			//
			
		}
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {

				
			}
			
		}		
	}

   [DefaultProperty("SelectedLanguage")]
   [ToolboxData("<{0}:ListBoxLanguages runat=server SelectedLanguage=''></{0}:ListBoxLanguages>")]
   public class ListBoxLanguages : System.Web.UI.WebControls.ListBox {
		private string _lingua = null;
		private string _voceSel = "-1";
		private string _tipomodu = "";
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new ACM.cmsarea08.Administration.Core.DBClass();
		private string _memo_test;
		private string _ex_lang ;
		public string ExcludedLang {
			get {
				return _ex_lang;
			}
			set {
				_ex_lang = value;
				
				this.CaricaDati();
			}
		}
		
		public bool EnableMultipleSelect {
			get {
				if(this.SelectionMode==ListSelectionMode.Multiple) return true;
				return false;
			}
			set {
				if(value==true)
					this.SelectionMode=ListSelectionMode.Multiple;
				else
					this.SelectionMode=ListSelectionMode.Single;
			}
		}
		
		private DataSet dsMenu {
			get {
				if(ViewState["AC_Lingue" + this.ID]==null)
					return null;
				else
					return (DataSet)ViewState["AC_Lingue" + this.ID];
			}
			set {
				ViewState["AC_Lingue" + this.ID] = value;
			}
		}

		public string SelectedLanguage
		{
		    get
		    {
		    	string selezionato = "";
		    	if(this.Items.Count>0 ) {
 		    		for(int i = 0 ; i<this.Items.Count; i ++) { 
			    		if(this.Items[i].Selected)
			    			selezionato+=this.Items[i].Value + "~";
		    		}
		    		if(selezionato.IndexOf("-1")>-1) selezionato="";
			    	if(selezionato.EndsWith("~"))
			    		selezionato = selezionato.Substring(0,selezionato.Length-1);
		    		ViewState[this.ID + "selectedlan"] = selezionato;
		    	} else {
		    		if(ViewState[this.ID + "selectedlan"]!=null)
		    			selezionato = ViewState[this.ID + "selectedlan"].ToString();
		    	}
		    	return selezionato;
		    }
		    set
		    {
		    	if(value == null) return;
		    	if(value.Trim()=="" || value.Length==0) return;
		    	string[] selLang = new string[0];
		    	if(value.IndexOf('~')==-1) 
		    		selLang = new string[1] { value.Trim()};
		    	else
		    		selLang = value.Split('~');
		    	if(this.Items.Count==0)
		    		this.CaricaDati();
		    	if(this.Items.Count>0) {
		    		for(int i=0;i<this.Items.Count;i++){
		    			foreach(string x in selLang) {
		    				if(this.Items[i].Value == x) {
		    					this.Items[i].Selected=true;
		    				}
		    			}
		    		}
		    	}
			    	ViewState[this.ID + "selectedlan"] = value;
//		    	} 	        
		    }
		}
		
		private void CaricaDati() {
			if(dsMenu==null) {
				dsMenu = dclass.GetDropAdminLanguage();
			}
			if(dsMenu==null) {
				this.Items.Clear();
				return;
			}
//			try {
			this.Items.Clear();
			string[] selezionati = new string[0];
			string s = "";
			if(ViewState[this.ID + "selectedlan"]!=null) {
				s = ViewState[this.ID + "selectedlan"].ToString();
			}
			if(s.Trim().Length>0 ) {
				if(s.IndexOf('~')==-1)
					selezionati= new string[1] { s.Trim() };
				else
					selezionati = s.Split('~');
			}
			
			this.Items.Add(new ListItem(" di sistema ","-1"));
			for(int i = 0; i<dsMenu.Tables[0].Rows.Count; i++){
				if(_ex_lang != null && _ex_lang.Contains(dsMenu.Tables[0].Rows[i]["cultureinfo"].ToString()))
					continue;
				ListItem mioI = new ListItem(dsMenu.Tables[0].Rows[i]["nome_lingua"].ToString(),
					dsMenu.Tables[0].Rows[i]["cultureinfo"].ToString());
				for(int vs = 0 ; vs<selezionati.Length; vs++)
					if(selezionati[vs]==mioI.Value)
					mioI.Selected=true;
				this.Items.Add(mioI);
			}
//			} catch {}
		}
		override protected void OnInit(EventArgs e)
		{
			
			base.OnInit(e);
			InitializeComponent();
			//this.SelectionMode= ListSelectionMode.Multiple;
			CaricaDati();
		}

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
		}
		
		private void Page_Load(object o , EventArgs e) {		
			if(!Page.IsPostBack) {		}
		}
		
		public void setCustomParameter(string customp) {
			string[] chiavi_valori = new string[0];
			if(customp.IndexOf('~')==-1)
				return;
			chiavi_valori = customp.Split('~');
			Type typethis = this.GetType();
			for(int i = 0 ; i<chiavi_valori.Length;i++) {
				string xst = "";
				string xsv = "";
				if(chiavi_valori[i].IndexOf('=')==-1)
					continue;
				xst = chiavi_valori[i].Substring(0, chiavi_valori[i].IndexOf('='));
				xsv = chiavi_valori[i].Substring(chiavi_valori[i].IndexOf('=')+1);
				MethodInfo method = typethis.GetMethod(xst.Trim(),BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
				System.Reflection.PropertyInfo membro = typethis.GetProperty(xst,BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
				if(method!=null) {
					method.Invoke(this,new object[] {xsv});
				} else if(membro!=null) {
					membro.SetValue(this,(object)xsv,null);
				} 
			}
		}
		
	}

}
